package com.cgbl.service.vm

import android.app.Application
import androidx.databinding.ObservableField
import api.UserServiceFactory
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.configs.PrefsManager
import com.robot.base.model.BaseResponse
import com.robot.base.model.UserInfoBean
import com.robot.base.util.ActivityUtils
import com.robot.base.util.arouter.ARouterUtil
import com.robot.base.util.arouter.ARouterUtil.goToActivity
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand


class MineViewModel(application: Application) : GLBaseViewModel(application) {

    val avatar = ObservableField<String>()

    val nickName = ObservableField<String>()

    val workNo = ObservableField<String>()
    val clickLogoutCommand = BindingCommand<Any>(BindingAction {
       logout()
    })

    init {
        UserServiceFactory.userInfo()
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<UserInfoBean?>?>(this) {
                override fun onNext(userInfoBeanBaseResponse: BaseResponse<UserInfoBean?>) {
                    PrefsManager.saveUserInfo(userInfoBeanBaseResponse.data)
                    refreshUserInfo()
                }
            })

    }

    private fun refreshUserInfo() {
        nickName.set(PrefsManager.getUserInfo().nickName)
        avatar.set(PrefsManager.getUserInfo().head)
        workNo.set("工号:  " + PrefsManager.getUserInfo().nickName)
    }


    private fun logout() {
        UserServiceFactory.logout()
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
                override fun onNext(userInfoBeanBaseResponse: BaseResponse<String>) {
                    PrefsManager.loginout()
                    ActivityUtils.finishAllActivities()
                    goToActivity(AppConstants.Router.Login.A_LOGIN_PASSWORD)
                }
            })
    }
}